package com.tz.dream.architect.mvp.framework.support;

import com.tz.dream.architect.mvp.framework.MvpPresenter;
import com.tz.dream.architect.mvp.framework.MvpView;

/**
 * 作者: Dream on 2018/3/16 21:53
 * QQ:510278658
 * E-mail:510278658@qq.com
 */

//代理模式-第二重代理-代理对象-绑定和解绑
//两个特点
//特点一：实现目标接口（可有可无）
//特点二：持有目标对象引用（必需）
public class ProxyMvpDelegateCallback<V extends MvpView, P extends MvpPresenter<V>> implements MvpDelegateCallback<V, P> {

    //特点二：持有目标对象引用（必需）->mvpCallback（实际上-MvpActivity）
    private MvpDelegateCallback<V, P> mvpCallback;

    public ProxyMvpDelegateCallback(MvpDelegateCallback<V, P> mvpCallback){
        this.mvpCallback = mvpCallback;
    }

    @Override
    public P createPresenter() {
        P presenter = this.mvpCallback.getPresenter();
        if (presenter == null){
            presenter = this.mvpCallback.createPresenter();
        }
        if (presenter == null){
            throw new NullPointerException("P层不能为空");
        }
        this.mvpCallback.setPresenter(presenter);
        return presenter;
    }

    @Override
    public P getPresenter() {
        return this.mvpCallback.getPresenter();
    }

    @Override
    public void setPresenter(P presenter) {
        this.mvpCallback.setPresenter(presenter);
    }

    @Override
    public V getMvpView() {
        return this.mvpCallback.getMvpView();
    }

    //添加两个重要的方法
    public void attachView(){
        getPresenter().attachView(getMvpView());
    }

    public void detachView(){
        getPresenter().detachView();
    }

}
